package com.dreamchaser.familydevice.config;

import com.dreamchaser.familydevice.annotation.IgnoreUrl;
import com.dreamchaser.familydevice.shiro.filter.ShiroFilterChainManager;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.method.HandlerMethod;
import org.springframework.web.servlet.mvc.method.RequestMappingInfo;
import org.springframework.web.servlet.mvc.method.annotation.RequestMappingHandlerMapping;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;

/***
 *
 *
 * @Author: ShaJie
 * Date: 2020/2/17 下午2:01
 * Description:
 *
 */
@Configuration
@Slf4j

public class ControllerConfig {


    @Autowired
    ShiroFilterChainManager shiroFilterChainManager;
    /**
     * 控制器ignore url获取
     * @return
     */
    @Bean(name = "ignoreUrls")
    public List<String> urls() {

        List<String> urls = new ArrayList<>();
        RequestMappingHandlerMapping mapping = SpringContextHolder.getBean(RequestMappingHandlerMapping.class);
        // 获取url与类和方法的对应信息
        Map<RequestMappingInfo, HandlerMethod> map = mapping
                .getHandlerMethods();
        for (Map.Entry<RequestMappingInfo, HandlerMethod> item : map.entrySet()) {
            log.info(item.getValue().getBeanType().getName());
            if (item.getValue().getBeanType().isAnnotationPresent(IgnoreUrl.class) || item.getValue().getMethod().isAnnotationPresent(IgnoreUrl.class)) {
                // 处理
                // 获取url的Set集合，一个方法可能对应多个url
                Set<String> patterns = item.getKey().getPatternsCondition().getPatterns();
                for (String url : patterns) {
                    //把结果存入静态变量中程序运行一次次方法之后就不用再次请求次方法
                    urls.add(url);
                }
            }
        }

        return urls;
    }
}
